﻿// Study0809.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
// 第八章 多态 运行时类型识别
//（1）dynamic_cast(2)typeid

#include <iostream>
#include <typeinfo>
using namespace std;

class Base
{
public:
	virtual ~Base() {}
	virtual void fun1();

};
void Base::fun1()
{
	cout << "调用Base类fun1函数" << endl;
}

class Derived1 :public Base
{
public:
	void fun1() override;
	virtual void fun2();

};

void Derived1::fun1()
{
	cout << "调用Derived1类fun1函数" << endl;
}
void Derived1::fun2()
{
	cout << "调用Derived1类fun2函数" << endl;
}

class Derived2:public Derived1
{
public:
	void fun1() override;
	void fun2() override;
	
};

void Derived2::fun1()
{
	cout << "调用Derived2类fun1函数" << endl;
}
void Derived2::fun2()
{
	cout << "调用Derived2类fun2函数" << endl;
}
void dyncast(Base* b)
{
	b->fun1();
	Derived1* d = dynamic_cast<Derived1*>(b);
	if (d!=nullptr)
	{
		d->fun2();
	}
}
void tyid(Base* b)
{
	const type_info& info1 = typeid(b);
	const type_info& info2 = typeid(*b);
	cout << "typeid(b):" << info1.name() << endl;
	cout << "typeid(*b):" << info2.name() << endl;
	if (info2==typeid(Base))
	{
		cout << "属于Base类对象" << endl;
	}
	else if (info2==typeid(Derived1))
	{
		cout << "属于Derived1类对象" << endl;
	}
	else if (info2 == typeid(Derived2))
	{
		cout << "属于Derived2类对象" << endl;
	}
}
int main()
{
	Base b;
	Derived1 d1;
	Derived2 d2;
	dyncast(&b);
	dyncast(&d1);
	dyncast(&d2);
	cout << "========================" << endl;
	tyid(&b);
	tyid(&d1);
	tyid(&d2);

	return 0;
}

